package com.eshop.web.controllers.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.eshop.common.constant.CoreConstant;
import com.eshop.frameworks.core.controller.BaseController;
import com.eshop.model.mongodb.ECartItem;
import com.eshop.model.mongodb.EShop;
import com.eshop.model.mongodb.EUser;
import com.eshop.model.mongodb.EUserAddress;
import com.eshop.model.mongodb.ShopAndGoods;
import com.eshop.service.mongodb.ECartItemService;
import com.eshop.service.mongodb.EShopService;
import com.eshop.service.mongodb.EUserAddressService;
import com.eshop.service.mongodb.ShippingService;
import com.eshop.service.mongodb.ShopAndGoodsService;

@Controller
@RequestMapping("/cart")
public class GoodsCarController extends BaseController{
	
	private static final Logger logger = Logger.getLogger(GoodsCarController.class);
	
	@Autowired
	private EShopService eshopService;
	@Autowired
	private ShippingService shippingService;
	@Autowired
	private ShopAndGoodsService shopAndGoodsService;
	@Autowired
	private ECartItemService ecartItemService;
	@Autowired
	private EUserAddressService euserAddressService;
	private Map<String, EShop> shopMap = new HashMap<String, EShop>();

	@RequestMapping("")
	public ModelAndView cart(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("/euser/cart.httl");
		setVar(mav);
		EUser user = (EUser) this.getSessionAttribute(request,
				CoreConstant.USER_SESSION_NAME);
		if (user == null) {
			mav.setViewName("redirect:/login");
			return mav;
		}
		// List<ECartItem> items = geItems(user.getId());
		Map<String, List<ECartItem>> itemMap = getItemsMap(user.getId());
		List<EUserAddress> addresses = euserAddressService.getAddressByUserId(user.getId());
		mav.addObject("user", user);
		mav.addObject("itemMap", itemMap);
		mav.addObject("addressList", addresses);

		return mav;
	}
	

	@RequestMapping("/delete/{id}")
	public ModelAndView deleteCartItem(HttpServletRequest request,
			@PathVariable("id") String id) {
		ModelAndView mav = new ModelAndView("redirect:/cart");
		EUser user = (EUser) this.getSessionAttribute(request,
				CoreConstant.USER_SESSION_NAME);
		setVar(mav);
		if (user == null) {
			return new ModelAndView("redirect:/login");
		}
		// List<ECartItem> items = geItems(user.getId());
//		ecartItem = ecartItemService.findById(ecartItem.getId(),ECartItem.class);
		ecartItemService.removeById(id, ECartItem.class);
//		ecartItemService.remove(ecartItem);
//		Map<String, List<ECartItem>> itemMap = getItemsMap(user.getId());
//		List<EUserAddress> addresses = euserAddressService.getAddressByUserId(user.getId());
//		mav.addObject("user", user);
//		mav.addObject("itemMap", itemMap);
//		mav.addObject("addressList", addresses);
		return mav;
	}
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addCart(@RequestBody ECartItem ecartItem,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			EUser user = (EUser) this.getSessionAttribute(request,CoreConstant.USER_SESSION_NAME);
			if (user == null) {
				return "FALSE";
			}
			ECartItem myItem = ecartItemService.getMyItem(ecartItem.getGoodsId(), user.getId());
			if (myItem != null) {
				myItem.setGoodsCount(myItem.getGoodsCount() + ecartItem.getGoodsCount());
				ecartItemService.save(myItem);
			} else {
				ecartItem.setAddTime(new Date());
				ecartItem.setUserId(user.getId());
				ecartItem.setStatus(0);
				ecartItemService.save(ecartItem);
			}
		} catch (Exception e) {
			logger.error("GoodsCarController.addCart", e);
		}
		return "SUCCESS";
	}
	
	@RequestMapping(value = "/changeCartCount", method = RequestMethod.POST)
	public ModelAndView changeCartCount(ECartItem ecartItem,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("redirect:/cart");
		EUser user = (EUser) this.getSessionAttribute(request,
				CoreConstant.USER_SESSION_NAME);
		setVar(mav);
		if (user == null) {
			return new ModelAndView("redirect:/login");
		}
		ecartItemService.updateCount(ecartItem.getId(),ecartItem.getGoodsCount());
//		Map<String, List<ECartItem>> itemMap = getItemsMap(user.getId());
//		List<EUserAddress> addresses = euserAddressService.getAddressByUserId(user.getId());
//		mav.addObject("user", user);
//		mav.addObject("itemMap", itemMap);
//		mav.addObject("addressList", addresses);
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value = "/changeCount", method = RequestMethod.POST)
	public String changeCount(@RequestBody ECartItem ecartItem,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			ecartItemService.updateCount(ecartItem.getId(), ecartItem.getGoodsCount());
		} catch (Exception e) {
			logger.error("GoodsCarController.addCart", e);
			return "FALSE";
		}
		return "SUCCESS";
	}
	
	@ResponseBody
	@RequestMapping(value = "/remove", method = RequestMethod.POST)
	public String delete(@RequestBody ECartItem ecartItem,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			ecartItemService.removeById(ecartItem.getId(), ECartItem.class);
		} catch (Exception e) {
			logger.error("GoodsCarController.addCart", e);
			return "FALSE";
		}
		return "SUCCESS";
	}
	
	@ResponseBody
	@RequestMapping(value = "/getMyECartItems", method = RequestMethod.POST)
	public List<ECartItem> getMyECartItems(HttpServletRequest request,
			HttpServletResponse response) {
		List<ECartItem> ecartItems = new ArrayList<ECartItem>();
		try {
			EUser user = (EUser) this.getSessionAttribute(request,CoreConstant.USER_SESSION_NAME);
			if(user==null){
				return null;
			}
			ecartItems = getMyItems(user.getId());
		} catch (Exception e) {
			logger.error("GoodsCarController.getMyECartItems", e);
		}
		return ecartItems;
	}

	private Map<String, List<ECartItem>> getItemsMap(String userId) {
		Map<String, List<ECartItem>> ecartMap = new HashMap<String, List<ECartItem>>();
		List<ECartItem> ecartItems = ecartItemService.getItems(userId);
		ShopAndGoods goods = null;
		EShop eshop = null;
		for (ECartItem item : ecartItems) {
			goods = shopAndGoodsService.findById(item.getGoodsId(),ShopAndGoods.class);
			item.setGoods(goods);
			eshop = eshopService.getEShopByUser(item.getShopId());
			item.setEshop(eshop);
			if (!ecartMap.containsKey(eshop.getShopName())) {
				ecartMap.put(eshop.getShopName(), new ArrayList<ECartItem>());
			}
			ecartMap.get(eshop.getShopName()).add(item);
		}
		return ecartMap;
	}

	private List<ECartItem> getMyItems(String userId) {
		shopMap = new HashMap<String, EShop>();
		List<ECartItem> ecartItems = new ArrayList<ECartItem>();
		ecartItems = ecartItemService.getItems(userId);
		ShopAndGoods goods = null;
		EShop eshop = null;
		for (ECartItem item : ecartItems) {
			goods = shopAndGoodsService.findById(item.getGoodsId(),ShopAndGoods.class);
			item.setGoods(goods);
			eshop = eshopService.getEShopByUser(item.getShopId());
			if (!shopMap.containsKey(item.getShopId())) {
				shopMap.put(item.getShopId(), eshop);
			}
			item.setEshop(eshop);
		}
		return ecartItems;
	}
}
